package il.ac.technion.cs236700.utils.CSV;

import java.util.Map;

/**
 * A class representing a separator string, which can be used for separating
 * elements of a sequence while printing it, without special case treatement of
 * the first or last element. For example, the following program prints a list
 * of its arguments separted by ", ", without using any conditionals.
 * 
 * <pre>
 * static void main(String[] args) {
 * 	Separator s = new Separator(&quot;, &quot;);
 * 	for (String a : args)
 * 		System.out.print(s + a);
 * }
 * </pre>
 */
public class Separator {
	private final String s;
	boolean first = true;

	public Separator(String s) {
		this.s = s;
	}

	@Override public String toString() {
		if (!first)
			return s;
		first = false;
		return "";
	}

	public static <T> boolean isEmpty(Iterable<T> items) {
		return !items.iterator().hasNext();
	}

	public static <T> String wrap(String wrap, Iterable<T> items, String between) {
		return wrap(wrap, wrap, items, between);
	}

	public static <T> String wrap(String begin, String end, Iterable<T> items, String between) {
		if (isEmpty(items))
			return "";
		String $ = begin;
		Separator s = new Separator(between);
		for (T t : items)
			$ += s + t.toString();
		return $ + end;
	}

	public static <Key, Value> String separateBy(Map<Key, Value> map, String between, String arrow) {
		String $ = "";
		Separator s = new Separator(between);
		for (Key k : map.keySet())
			$ += s + k.toString() + arrow + map.get(k);
		return $;
	}

	public static <T> String separateBy(Iterable<T> ts, String between) {
		String $ = "";
		Separator s = new Separator(between);
		for (T t : ts)
			$ += s + t.toString();
		return $;
	}

	public static String separateBy(Object[] os, String between) {
		StringBuffer $ = new StringBuffer("");
		Separator s = new Separator(between);
		for (Object o : os)
			$.append(s).append(o);
		return $.toString();
	}

	static void main(String[] args) {
		Separator s = new Separator(", ");
		for (String a : args)
			System.out.print(s + a);
	}

	public static String separateBy(int[] is, String between) {
		String $ = "";
		Separator s = new Separator(between);
		for (int i : is)
			$ += s.toString() + i;
		return $;
	}

	public static String separateBy(short[] is, String between) {
		String $ = "";
		Separator s = new Separator(between);
		for (short i : is)
			$ += s.toString() + i;
		return $;
	}
}
